<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="分类名" prop="categoryName">
        <el-input v-model="dataForm.categoryName" placeholder="分类名"></el-input>
      </el-form-item>
      <el-upload :action="url" accept=".jpg, .jpeg, .png" :before-upload="beforeUploadHandle" :on-success="handleSuccess" id="dialog">
        <el-image v-if="dataForm.categoryIcon" v-model="dataForm.categoryIcon" :src="dataForm.categoryIcon" style="border: 5px double black;"></el-image>
        <br/>
        <el-button type="success" size="mini">点击上传</el-button>
      </el-upload>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        url: '',
        visible: false,
        dataForm: {}
      }
    },
    methods: {
      init (id) {
        this.visible = true
        this.url = this.$http.adornUrl('/admin-interfaces/file/upload')
        if (id !== undefined) {
          this.$http({
            url: this.$http.adornUrl(`/mall-wares/wares/category/queryCategoryById/${id}`),
            method: 'get'
          }).then(({data}) => {
            this.dataForm = data.data
          })
        }
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl('/mall-wares/wares/category/saveOrUpdateCategory'),
              method: 'post',
              data: this.dataForm
            }).then(({data}) => {
              if (data.data === true && data.code === 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message({
                  showClose: true,
                  message: data.message,
                  type: 'warning',
                  center: true
                })
              }
            })
          }
        })
      },
      // 上传前处理图片尺寸
      beforeUploadHandle (file) {
        return new Promise((resolve, reject) => {
          // 创建一个 Image 对象
          const image = new Image()
          const reader = new FileReader()
          // 读取文件的数据
          reader.readAsDataURL(file)
          // 文件读取成功后进行压缩处理
          reader.onload = (event) => {
            image.src = event.target.result
            // 当图片加载完成后进行压缩
            image.onload = () => {
              const canvas = document.createElement('canvas')
              const context = canvas.getContext('2d')
              // 计算压缩后的尺寸
              const maxWidth = 200 // 设置最大宽度
              const maxHeight = 200 // 设置最大高度
              let width = image.width
              let height = image.height
  
              if (width > height) {
                if (width > maxWidth) {
                  height *= maxWidth / width
                  width = maxWidth
                }
              } else {
                if (height > maxHeight) {
                  width *= maxHeight / height
                  height = maxHeight
                }
              }
              // 设置 canvas 的尺寸
              canvas.width = width
              canvas.height = height
              // 进行图片压缩
              context.drawImage(image, 0, 0, width, height)
              // 将压缩后的图片转为 Blob 格式
              canvas.toBlob((blob) => {
                // 创建一个新的 File 对象，替换上传的文件对象
                const compressedFile = new File([blob], file.name, { type: blob.type })
                // 将处理后的文件传递给上传组件
                resolve(compressedFile)
              }, file.type || 'image/jpeg', 0.9) // 设置压缩质量
            }
          }
          // 如果文件读取失败，则直接传递原始文件
          reader.onerror = () => {
            resolve(file)
          }
        })
      },
      handleSuccess (response) {
        if (response.code === 200) {
          this.dataForm.categoryIcon = response.data.filePath
          this.$message({
            message: '更换头像成功',
            type: 'success',
            duration: 1500
          })
        }
      }
    }
  }
</script>
<style>
#dialog{
  width: 50%;
  height: 65%;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
}
</style>